﻿/*
 * ITask.cpp
 *
 *  Created on: 2016年2月22日
 *      Author: Administrator
 */

#include "gc.h"
namespace eyas{
namespace gc{

boost::mutex& _mutex(){
	static boost::mutex _mutex;
	return _mutex;
}
int& _capacity(){
	static int capacity_ = 0;
	return capacity_;
}

//
// memory_pool_manager
//
memory_pool_manager::~memory_pool_manager() {
	//info();
	cleanup();
	//info();
	shutdown();
	//info();
}

void memory_pool_manager::register_memory(memory_pool* pMemoryPool) {
	boost::recursive_mutex::scoped_lock lock(this->mutex_);
	_memoryPools[pMemoryPool->get_size()] = pMemoryPool;
}

void memory_pool_manager::unregister_memory(memory_pool* pMemoryPool) {
	boost::recursive_mutex::scoped_lock lock(this->mutex_);
	_memoryPools.erase(pMemoryPool->get_size());
}

void memory_pool_manager::cleanup() {
	boost::recursive_mutex::scoped_lock lock(this->mutex_);
	for (MEMORYPOOLS::iterator i = _memoryPools.begin();
			i != _memoryPools.end(); i++) {
		(i->second)->cleanup();
	}
}

//void memory_pool_manager::info() {
//	for (MEMORYPOOLS::iterator i = _memoryPools.begin();
//			i != _memoryPools.end(); i++) {
//		(i->second)->info();
//	}
//}

memory_pool_manager::memory_pool_manager() {

}

void memory_pool_manager::shutdown() {
	boost::recursive_mutex::scoped_lock lock(this->mutex_);
	while (_memoryPools.size() > 0) {
		delete _memoryPools.begin()->second;
	}
}


//
// memory_pool
//
memory_pool::memory_pool(size_t size) {
	_pEntries = NULL;
	_created = 0;
	_used = 0;
	_size = size >= sizeof (memory_pool_entry) ? size : sizeof (memory_pool_entry);
	memory_pool_manager::instance()->register_memory(this);

	//printf("memory_pool:%d\n", _size);
}

memory_pool::~memory_pool() {
	//printf("~memory_pool:%d\n", _size);
	cleanup();
	//assert(_used == 0);
	memory_pool_manager::instance()->unregister_memory(this);
}

void memory_pool::cleanup() {
	boost::recursive_mutex::scoped_lock lock(this->mutex_);
	memory_pool_entry *pCurrent = _pEntries;
	while (pCurrent != NULL) {
		_pEntries = _pEntries->pNext;
		::operator delete((void *) pCurrent);
		pCurrent = _pEntries;
		_created--;
	}
}

size_t memory_pool::get_size() {
	return _size;
}





EYAS_GC_API void init(){
	_mutex();
	_capacity();
	memory_pool_manager::instance();
}
EYAS_GC_API void clean(){

}
EYAS_GC_API void capacity(int cap){
	_capacity() = cap;
}

}
}
